<template>
  <div>
    <h2>数据表格</h2>
    <div>
      <input v-model="newName" placeholder="姓名" />
      <input type="number" v-model.number="newAge" placeholder="年龄" />
      <button @click="addPerson">添加</button>
    </div>
    <table border="1">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(person, index) in sortedPeople" :key="person.name">
          <td>{{ person.name }}</td>
          <td>{{ person.age }}</td>
          <td><button @click="deletePerson(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      newName: '',
      newAge: null,
      people: []
    };
  },
  computed: {
    sortedPeople () {
      return this.people.slice().sort((a, b) => a.age - b.age);
    }
  },
  methods: {
    addPerson () {
      if (this.newName && this.newAge !== null) {
        this.people.push({ name: this.newName, age: this.newAge });
        this.newName = '';
        this.newAge = null;
      } else {
        alert('请输入姓名和年龄');
      }
    },
    deletePerson (index) {
      this.people.splice(index, 1);
    }
  }
};
</script>

<style scoped>
input {
  margin-right: 10px;
}

button {
  margin-left: 10px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 8px;
  text-align: left;
}
</style>